layui.use(['jquery','table','layer','laydate','form','upload'],function () {
    var $ = layui.jquery;
    var table = layui.table;
    var layer = layui.layer;
    var laydate = layui.laydate;
    var form = layui.form;
    var upload = layui.upload;

    laydate.render({
        elem:"#registerDate",
        type:"date",
        tigger:"click"
    });

    //树
    var zTree;
    var demoIframe;

    var setting = {
        view: {
            dblClickExpand: false
        },
        data: {
            simpleData: {
                enable: true,  //true 、 false 分别表示 使用 、 不使用 简单数据模式
                idKey:"id",   //节点数据中保存唯一标识的属性名称
                pIdKey:"parentId",    //节点数据中保存其父节点唯一标识的属性名称
                rootPId: -1  //用于修正根节点父节点数据，即 pIdKey 指定的属性值
            },
            key: {
                enable: true,
                name: "deptName"  //zTree 节点数据保存节点名称的属性名称  默认值："name"
            }
        },
        check: {
            enable: false,
            nocheckInherit: true   //当父节点设置 nocheck = true 时，设置子节点是否自动继承 nocheck = true
        },
        callback: {
            //onRightClick: onRightClick,
            // beforeRemove: beforeRemove,//点击删除时触发，用来提示用户是否确定删除（可以根据返回值 true|false 确定是否可以删除）
            // beforeEditName: beforeEditName,//点击编辑时触发，用来判断该节点是否能编辑
            //beforeRename: beforeRename,//编辑结束时触发，用来验证输入的数据是否符合要求(也是根据返回值 true|false 确定是否可以编辑完成)
            // beforeDrag: beforeDrag,//用户禁止拖动节点
            onClick: chooseNode,
        }
    };
    $(document).ready(function () {
        $.ajax({
            type:"post",
            dataType:"json",
            url:"/JsPeopleList/selectJsDeptName",
            success:function (data) {
                //console.log(data);
                zTree = $.fn.zTree.init($("#tree"), setting, data.data); //初始化树
                zTree.expandAll(true);   //true 节点全部展开、false节点收缩
            }
        });
        demoIframe = $("#rMenu");

    });

    select("/JsPeopleList/selectJsUser?account="+''+"&trueName="+''+"&deptName="+''+"&registerDate="+'');
    function select(url) {
        table.render({
            elem:"#root",
            url:url,
            toolbar:"#toptool",
            defaultToolbar: ['','',''],
            page:true,
            limit:5,
            limits:[5,10,15,20],
            size: 'lg',
            cols:[[
                {type:"checkbox",align:"center"},
                {type:"numbers",title:"序号",align:"center"},
                {field:"trueName",title:"用户姓名",align:"center"},
                {field:"acatarUrl",title:"用户头像",align:"center",templet:function (data) {
                        return '<img src='+data.acatarUrl+' />';
                    }},
                {field:"sex",title:"性别",align:"center"},
                {field:"account",title:"用户账号",align:"center"},
                {field:"deptName",title:"所属部门",align:"center"},
                {field:"enabled",title:"是否启用",align:"center",templet:function (data) {
                        if(data.enabled==1){
                            var radio1 = '<a href="javascript:updateStatus('+data.userId+','+data.status+','+data.enabled+');"><input class="layui-input swi" type="checkbox" name="enable" lay-skin="switch" lay-text="启用|停用" lay-filter="switchTest" value="' + data.enable + '" checked></a>';
                        }else{
                            var radio1 = '<a href="javascript:updateStatus('+data.userId+','+data.status+','+data.enabled+');"><input class="layui-input swi" type="checkbox" name="enable" lay-skin="switch" lay-text="启用|停用" lay-filter="switchTest" value="' + data.enable + '"></a>';
                        }
                        return radio1;
                    }},
                {field:"status",title:"账号状态",align:"center",templet:function (data) {
                        if(data.status==1){
                            var radio2 = '<a href="javascript:updateStatus('+data.userId+','+data.status+','+data.enabled+');"><input class="layui-input swi" type="checkbox" name="status" lay-skin="switch" lay-text="使用中|封停" lay-filter="switchTest" value="' + data.status + '" checked></a>';
                        }else if(data.status==4){
                            var radio2 = '<a href="javascript:updateStatus('+data.userId+','+data.status+','+data.enabled+');"><input class="layui-input swi" type="checkbox" name="status" lay-skin="switch" lay-text="使用中|封停" lay-filter="switchTest" value="' + data.status + '"></a>';
                        }
                        return radio2;
                    }},
                {field:"registerDatee",title:"注册时间",align:"center"},
                {title:"操作",align:"center",templet:function (data) {
                        return "<div>" +
                            "<a href='javascript:chakan(" + data.userId + ");' style='color: #0EAA9E;margin-right: 10px'>查看</a>" +
                            "<a href='javascript:quanxian(" + data.userId + ");' style='color: #0EAA9E'>权限</a><br/>" +
                            "<a href='javascript:bianji("+data.userId+");' style='color: #0EAA9E; margin-right: 10px'>编辑</a>" +
                            "<a href='javascript:fengting(\""+data.userId+"\",\""+data.account+"\",\""+data.status+"\");' style='color: #0EAA9E'>封停</a>" +
                            "</div>";
                    }}
            ]]
        })
    };
    //点击节点，展示对应类别下商品信息
    function chooseNode(event, treeId, treeNode) {
        var zTree = $.fn.zTree.getZTreeObj(treeId);
        var nodes = zTree.getSelectedNodes();
        var deptName = nodes[0].deptName;
        if(deptName=="所有部门"){
            select("/JsPeopleList/selectJsUser?account="+''+"&trueName="+''+"&deptName="+''+"&registerDate="+'');
        }else{
            select("/JsPeopleList/selectJsUser?account="+''+"&trueName="+''+"&deptName="+deptName+"&registerDate="+'');
        }
    };

    //搜索
    $("#sousuo").click(function () {
        var account = $('#account').val();
        var trueName = $('#trueName').val();
        var deptName = $('#deptName').val();
        var registerDate = $('#registerDate').val();
        select("/JsPeopleList/selectJsUser?account="+account+"&trueName="+trueName+"&deptName="+deptName+"&registerDate="+registerDate);
    });
    //重置
    $("#chongzhi").click(function () {
        select("/JsPeopleList/selectJsUser?account="+''+"&trueName="+''+"&deptName="+''+"&registerDate="+'');
    });
    //更改账号状态
    updateStatus = function updateStatus(userId,status,enabled) {
        if(status==1){
            var status1 = 4;
        }else{
            var status1 = 1;
        }

        if(enabled==1){
            var enabledd=2;
        }else{
            var enabledd=1;
        }
        var unsealDate = new Date();
        unsealDate = getTime(unsealDate);
        var endDate = new Date();
        endDate=getTime100(endDate);
        var json ={
            userId:userId,
            status:status1,
            enabled:enabledd,
            unsealDate:unsealDate,
            endDate:endDate,
            type:2,
            remarks:"紧急封停"
        };

        $.ajax({
            type:"post",
            dataType:"json",
            data:json,
            url:"/JsPeopleList/updateStatus",
            success:function (data) {
                if(data){
                    layer.msg("更改成功");
                }else{
                    layer.msg("更改失败");
                }
                location.reload();
            }
        });
    };
    //高级检索
    $("#jiansuo").click(function () {
        var obj;
        layer.open({
            type:2,
            shode:0,
            title:"高级检索",
            content:"/jurisdiction/jurisdiction-people-list-search.html",
            area:["600px","600px"],
            btn:["确定","取消"],
            yes:function (index) {
                var email = obj.find("#email").val();
                var phone = obj.find("#phone").val();
                var idCard = obj.find("#idCard").val();
                var status = obj.find("#status").val();
                var sex = obj.find("#sex").val();
                var enabled = obj.find("#enabled").val();
                select("/JsPeopleList/selectSearchJsUser?email="+email+"&phone="+phone+"&idCard="+idCard+"&status="+status+"&sex="+sex+"&enabled="+enabled);
                layer.close(index);
            },btn2:function (index) {
                layer.close(index);
            },success:function (layero,index) {
                obj = layero.find('iframe').contents();
            }
        })
    });

    //查看用户信息
    chakan = function chakan(userId){
        $.ajax({
            type:"post",
            dataType:"json",
            data:{"id":userId},
            url:"/JsPeopleList/selectJsUserById",
            success:function (data) {
               // console.log(data);
                cha(data);
            }
        })
    };
    //查看后弹出赋值
    function cha(data) {
        var obj;
        layer.open({
            type:2,
            shode:0,
            maxmin:true,
            title:"查看用户信息",
            content:"/jurisdiction/jurisdiction-see-uesr.html",
            area:["1000px","620px"],
            btn:["关闭"],
            yes:function (index) {
                layer.close(index);
            },success:function (layero,index) {
                obj = layero.find('iframe').contents();
                obj.find("#acatarUrl").attr('src',data.data.acatarUrl);
                obj.find("#account").val(data.data.account);
                obj.find("#trueName").val(data.data.trueName);
                obj.find("#sex").val(data.data.sex);
                obj.find("#phone").val(data.data.phone);
                obj.find("#birthDate").val(data.data.birthDate);
                obj.find("#deptName").val(data.data.deptName);
                obj.find("#registerDate").val(data.data.registerDate);
                obj.find("#registerIp").val(data.data.registerIp);
                obj.find("#email").val(data.data.email);
                obj.find("#freestyle").val(data.data.freestyle);
            }
        });
    };
    //权限
    quanxian = function quanxian(userId) {
        $.ajax({
            type:"post",
            dataType:"json",
            data:{"userId":userId},
            url:"/JsPeopleList/selectUserSettings",
            success:function (data) {
                quan(data);
            }
        })
    };
    function quan(data){
        var obj;
        layer.open({
            type:2,
            shode:0,
            maxmin:true,
            title:"权限设置",
            content: "/jurisdiction/jurisdiction-people-list-settings.html",
            area:["900px","500px"],
            success:function (layero,index) {
                obj = layero.find('iframe').contents();
                obj.find("#userId").val(data.data[0].userId);
                obj.find("#trueName").val(data.data[0].trueName);
                //obj.find("input[name=authorityId]").val(data.data[0].authorityId);
                obj.find("#remark").val(data.data[0].remark);

                var shu1 = data.data;

                obj.find("#quanxian").children("input").each(function (i,e) {
                    for(var i =0;i<shu1.length;i++){
                        if($(this).attr('txt')==shu1[i].authorityId){
                            $(this).next("div").click();
                        }
                    }
                });
            }
        });
    };
    //编辑
    //查看用户信息
    bianji = function bianji(userId){
        $.ajax({
            type:"post",
            dataType:"json",
            data:{"id":userId},
            url:"/JsPeopleList/selectJsUserById",
            success:function (data) {
                //console.log(data);
                Tbianji(data);
            }
        })
    };
    //查看后弹出赋值
    function Tbianji(data) {
        var obj;
        layer.open({
            type:2,
            shode:0,
            maxmin:true,
            title:"编辑用户信息",
            content:"/jurisdiction/jurisdiction-see-uesr-edit.html",
            area:["1000px","620px"],
            btn:["编辑","取消"],
            yes:function (index) {
                var json={
                    acatarUrl:obj.find("#acatarUrl").attr("src"),
                    userId:obj.find("#userId").val(),
                    account:obj.find("#account").val(),
                    trueName:obj.find("#trueName").val(),
                    sex:obj.find("#sex").val(),
                    phone:obj.find("#phone").val(),
                    birthDate:obj.find("#birthDate").val(),
                    deptId:obj.find("#deptId").val(),
                    email:obj.find("#email").val(),
                    freestyle:obj.find("#freestyle").val()
                };
                $.ajax({
                    type:"post",
                    dataType:"json",
                    data:json,
                    url:"/JsPeopleList/updateUser",
                    success:function (data) {
                        if(data){
                            layer.msg("编辑成功");
                            layer.close(index);
                        }else{
                            layer.msg("编辑失败");
                            layer.close(index);
                        }
                    }
                });
                location.reload();
            },
            btn2:function(index){
                layer.close(index);
            },
            success:function (layero,index) {
                obj = layero.find('iframe').contents();
                obj.find("#userId").val(data.data.userId);
                obj.find("#acatarUrl").attr('src',data.data.acatarUrl);
                obj.find("#account").val(data.data.account);
                obj.find("#trueName").val(data.data.trueName);
                obj.find("#phone").val(data.data.phone);
                obj.find("#birthDate").val(data.data.birthDate);
                obj.find("#registerDate").val(data.data.registerDate);
                obj.find("#registerIp").val(data.data.registerIp);
                obj.find("#email").val(data.data.email);
                obj.find("#freestyle").val(data.data.freestyle);
                var deptName = '';
                if(data.data.deptId==1){
                    deptName="管理部";
                }else if(data.data.deptId==2){
                    deptName="人事部";
                }else if(data.data.deptId==3){
                    deptName="运营部";
                }else{
                    deptName="教师部";
                }
                var sex = "";
                if(data.data.sex=="男"){
                    sex="男";
                }else{
                    sex="女"
                }
                selectLay(obj,data.data.sex,sex,"#sex");
                selectLay(obj,data.data.deptId,deptName,"#deptId")
            }
        });
    };
    //加入lay-value的下拉框矫正
    function selectLay(obj,layValue,value,select) {
        obj.find(select).children().each(function () {
            if ($(this).val() == layValue) {
                var status = 'dd[lay-value=' + layValue + ']';
                obj.find(select).siblings("div.layui-form-select").find('dl').find(status).click();
                $(this).parent().append('<option value="'+layValue+'" selected>' + value + '</option>');
            }
        })
    }
    //封停
    fengting = function fengting(userId,account,status) {
       if(status==4){
            layer.msg("此账号已被封停");
       }else{
           var id=userId;
           //console.log(id);
           var obj;
           layer.open({
               type:2,
               shode:0,
               maxmin:true,
               title:"账户封停",
               content:"/jurisdiction/jurisdiction-people-list-shutdown.html",
               area:['500px','370px'],
               btn:['确定','取消'],
               yes:function(index){
                   var days = obj.find("#days").val();
                   var reason = obj.find("#reason").val();
                   var startDate = new Date();
                   startDate = getTime(startDate);
                   var endDate = new Date();
                   endDate = getTimes(endDate,days);
                   var status = "4";
                   var enabled = "2";
                   var type = "3";

                   var json = {
                       userId:id,
                       type:type,
                       reason:reason,
                       startDatee:startDate,
                       endDatee:endDate,
                       days:days,
                       status:status,
                       enabled:enabled
                   };
                   //console.log(json);
                   $.ajax({
                       type:"post",
                       dataType:"json",
                       data:json,
                       url:"/JsPeopleList/insertUserClosure",
                       success:function (data) {
                           //console.log(data);
                           if(data){
                               layer.msg("封停成功");
                               location.reload();
                           }else{
                               layer.msg("封停失败");
                           }
                       }
                   });
               },
               btn2:function(index){
                   layer.close(index);
               },
               success:function (layero,index) {
                   obj = layero.find('iframe').contents();
                   obj.find("#account").val(account);
               }
           })
       }
    };

    //顶部时间
    function getTimes(date,days){
        var year = date.getFullYear(); //获取完整的年份(4位,1970-????)
        var month = date.getMonth()+1; //获取当前月份(0-11,0代表1月)
        var today = date.getDate(); //获取当前日(1-31)
        var hour = date.getHours(); //获取当前小时数(0-23)
        var minute = date.getMinutes(); //获取当前分钟数(0-59)
        var second = date.getSeconds(); //获取当前秒数(0-59)
        days = parseInt(days);
        today = parseInt(today);
        month = parseInt(month);
        year = parseInt(year);
        if(days=="1"){
            today = today+days;
            if(today>32|today>31){
                if(month=1|3|5|7|8|10|12){
                    month+=1;
                }else if(month=4|6|9|11){
                    month+=1;
                }else{
                    month+=1;
                }
            }
        }else if(days=="30"){
            month = month+1;
            if(month>13){
                year=year+1;
            }
        }else if(days=="365"){
            year=year+1;
        }else{
            year=year+100;
        }
        var nowTime;
        nowTime = year+'-'+fillZero(month)+'-'+fillZero(today)+' '+fillZero(hour)+':'+fillZero(minute)+':'+fillZero(second);
        return nowTime;
    };
    //顶部时间
    function getTime(date){
        var year = date.getFullYear(); //获取完整的年份(4位,1970-????)
        var month = date.getMonth()+1; //获取当前月份(0-11,0代表1月)
        var today = date.getDate(); //获取当前日(1-31)
        var hour = date.getHours(); //获取当前小时数(0-23)
        var minute = date.getMinutes(); //获取当前分钟数(0-59)
        var second = date.getSeconds(); //获取当前秒数(0-59)
        var nowTime;
        nowTime = year+'-'+fillZero(month)+'-'+fillZero(today)+' '+fillZero(hour)+':'+fillZero(minute)+':'+fillZero(second);
        return nowTime;
    };
    //顶部时间
    function getTime100(date){
        var year = date.getFullYear()+100; //获取完整的年份(4位,1970-????)
        var month = date.getMonth()+1; //获取当前月份(0-11,0代表1月)
        var today = date.getDate(); //获取当前日(1-31)
        var hour = date.getHours(); //获取当前小时数(0-23)
        var minute = date.getMinutes(); //获取当前分钟数(0-59)
        var second = date.getSeconds(); //获取当前秒数(0-59)
        var nowTime;
        nowTime = year+'-'+fillZero(month)+'-'+fillZero(today)+' '+fillZero(hour)+':'+fillZero(minute)+':'+fillZero(second);
        return nowTime;
    };
    //时间的为零操作
    function fillZero(str){
        var realNum;
        if(str<10){
            realNum	= '0'+str;
        }else{
            realNum	= str;
        }
        return realNum;
    };

    $("#shuaxin").click(function () {
        location.reload();
    });
    //跳转
    goBack=function goBack(){
        //通过页面查找iframe
        parent.$('#recordLog').val($('#examine').text());
        parent.before();
        return false;
    };
});